﻿using System;
using System.Collections.Generic;
using System.Linq;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.HttpUtility;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.Card;
using Senparc.Weixin.MP.CommonAPIs;
using WeChatCardProxy.WebApiControllers.Model;
using WeChatCardProxy.WebApiEntity;
using ZLWeb.WebApiEntityBase;
using Access_token = WeChatCardProxy.WebApiEntity.Access_token;
using ZilLion.Service.Core.Infrastructure.Base;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.WeChatCardProxy.Domain;
using Microsoft.AspNetCore.Authorization;
using ZilLion.Service.Core.ConfigManager.Manager;
using ZilLion.Service.Core.CRMUnities.Config;

namespace WeChatCardProxy.WebApiControllers.Controllers
{
    /// <summary>
    ///
    /// </summary>
    [Route("Api/Component")]
    [AllowAnonymous]
    public class ComponentController : ZilLionControllerBase
    {
        public static string _appId = string.Empty;
        public static string _appSecret = string.Empty;
        protected IVerify_TicketRepository pverifyservice { get; set; }
        protected IAccess_tokenRepository tokenRepository { get; set; }
        protected IAuthorization_infoRepository infoRepository { get; set; }
        protected IAppid_MsgRepository MsgRepository { get; set; }
        /// <summary>
        ///     构造
        /// </summary>
        /// <param name="gsService"></param>
        public ComponentController(IVerify_TicketRepository _pverifyservice,
            IAccess_tokenRepository _tokenRepository,
            IAuthorization_infoRepository _infoRepository, IAppid_MsgRepository _MsgRepository)
        {
            pverifyservice = _pverifyservice;
            tokenRepository = _tokenRepository;
            infoRepository = _infoRepository;
            MsgRepository = _MsgRepository;
            _appId =ZilLionConfigurationManager.GetConfigInstance<WeChatCardProxyConfig>().ComponentAppid;
            _appSecret = ZilLionConfigurationManager.GetConfigInstance<WeChatCardProxyConfig>().ComponentAppSecret;
        }

        [HttpPost("UpdateVerify_Ticket")]
        public ResponseResultInfo UpdateVerify_Ticket(Verify_Ticket vticket)
        {
            //var pverifyservice = ClassFactory.GetInstance<IVerify_TicketRepository>();
            var item = pverifyservice.GetVerify_Ticket(vticket);
            if (item == null)
            {
                vticket.CreateTime = DateTime.Now;
                vticket.UpdateTime = DateTime.Now;
                pverifyservice.InsertVerify_Ticket(vticket);
            }
            else
            {
                item.UpdateTime = DateTime.Now;
                pverifyservice.UpdateVerify_Ticket(item);
            }
            return new ResponseResultInfo();
        }

        [HttpGet("GetVerify_Ticket")]
        public Verify_Ticket GetVerify_Ticket(string appid)
        {
            var item = pverifyservice.GetVerify_Ticket(appid);
            return item;
        }

        [HttpGet("GetAccess_token")]
        public Access_token GetAccess_token()
        {
            var item = tokenRepository.GetAccess_token(new Access_token() {component_appid = _appId});
            //if (item == null)
            //{
            //    Verify_Ticket vt = GetVerify_Ticket(_appId);
            //    string ip = Request.RequestUri.Host;
            //    ComponentAccessTokenResult TokenResult = ComponentApi.GetComponentAccessToken(_appId, _appSecret, vt.ComponentVerifyTicket, 10000);
            //    Access_token at=new Access_token();
            //    at.component_appid = _appId;
            //    at.component_access_token = TokenResult.component_access_token;
            //    at.UpdateTime = DateTime.Now;
            //    at.expires_Time = DateTime.Now.AddSeconds(TokenResult.expires_in);
            //    accesstokenservice.InsertAccess_token(at);
            //    item = at;
            //}
            return item ?? new Access_token();
        }

        [HttpGet("GetAccess_tokens")]
        public Access_tokens GetAccess_tokens()
        {
            var item = tokenRepository.GetAccess_token();
            Access_tokens ats = new Access_tokens();
            ats.access_tokens = item;
            return ats;
        }

        [HttpGet("GetAuthorization_infos")]
        public Authorization_infos GetAuthorization_infos()
        {
            var item = infoRepository.GetAuthorization_infos();
            Authorization_infos ats = new Authorization_infos();
            ats.authorization_infos = item.ToList();
            return ats;
        }

        [HttpPost("InsertAccessToken")]
        public ResponseResultInfo InsertAccessToken(Access_token item)
        {
            tokenRepository.InsertAccess_token(item);
            return new ResponseResultInfo();
        }

        [HttpPost("UpdateAccess_token")]
        public ResponseResultInfo UpdateAccess_token(Access_token token)
        {
            var item = tokenRepository.GetAccess_token(token);
            if (item == null)
            {
                token.UpdateTime = DateTime.Now;
                tokenRepository.InsertAccess_token(token);
            }
            else
            {
                token.UpdateTime = DateTime.Now;
                tokenRepository.UpdateAccess_token(token);
            }
            return new ResponseResultInfo();
        }

        [HttpPost("UpdateAuthorization_info")]
        public ResponseResultInfo UpdateAuthorization_info(WeChatCardProxy.WebApiEntity.Authorization_info info)
        {
            if (!infoRepository.GetValideAuthorization_info(info.authorizer_appid))
            {
                return new ResponseResultInfo() {Errormodel = new ErrorModel() {desc = "该appid未注册！"}};
            }
            var item = infoRepository.GetAuthorization_info(info);
            if (item == null)
            {
                info.UpdateTime = DateTime.Now;
                infoRepository.InsertAuthorization_info(info);
            }
            else
            {
                info.UpdateTime = DateTime.Now;
                infoRepository.UpdateAuthorization_info(info);
            }
            return new ResponseResultInfo();
        }

       [HttpGet("GetAuthorization_info")]
        public WeChatCardProxy.WebApiEntity.Authorization_info GetAuthorization_info(string Authorization_appid)
        {
            if (!infoRepository.GetValideAuthorization_info(Authorization_appid))
            {
                return new WeChatCardProxy.WebApiEntity.Authorization_info()
                {
                    Errormodel = new ErrorModel() {desc = "该appid未注册！"}
                };
            }
            var item =
                infoRepository.GetAuthorization_info(new WeChatCardProxy.WebApiEntity.Authorization_info()
                {
                    authorizer_appid = Authorization_appid
                });
            return item ??
                   new WeChatCardProxy.WebApiEntity.Authorization_info()
                   {
                       Errormodel = new ErrorModel() {desc = "无该appid！"}
                   };
        }

        [HttpGet("GetAuthorization_Configinfo")]
        public Authorization_Config GetAuthorization_Configinfo(string Authorization_appid)
        {
            Authorization_Config domain = infoRepository.GetAuthorization_info(Authorization_appid);
            return domain;
        }

        [HttpPost("SaveAppMsg")]
        public ResponseResultInfo SaveAppMsg(Appid_Msg Msg)
        {
            MsgRepository.InsertAppid_Msg(Msg);
            return new ResponseResultInfo();
        }

        [HttpGet("GetAppid_Msgs")]
        public ResponseResultInfo GetAppid_Msgs()
        {
            List<Appid_Msg> Msgs = MsgRepository.GetAppid_Msgs();
            Appid_Msgs ats = new Appid_Msgs();
            ats.appid_Msgs = Msgs;
            return ats;
        }

        [HttpPost("DeleteAppid_Msg")]
        public ResponseResultInfo DeleteAppid_Msg(Appid_Msg Msg)
        {
            Msg.Msg_deldate = DateTime.Now;
            Msg.Msg_del = 1;
            MsgRepository.UpdateAppid_Msg(Msg);
            return new ResponseResultInfo();
        }


        [HttpGet("QueryCode")]
        public CodeDetail QueryCode(string appid, string code)
        {
            try
            {
                WeChatCardProxy.WebApiEntity.Authorization_info Authorizate = GetAuthorization_info(appid);
                CodeModel codemodel = QCode(Authorizate.authorizer_access_token, code);
                if (codemodel.errcode != 0)
                    return new CodeDetail() {Errormodel = new ErrorModel() {desc = codemodel.errmsg}};
                CodeDetail coded = ToCodeDetail(codemodel);
                return coded;
            }
            catch (Exception exe)
            {
                if (exe.Message != null)
                    return new CodeDetail() {Errormodel = new ErrorModel() {desc = exe.Message}};
            }
            return new CodeDetail();
        }

        [AllowAnonymous]
        private CodeDetail ToCodeDetail(CodeModel codemodel)
        {
            CodeDetail code = new CodeDetail();
            code.balance = codemodel.card.balance;
            code.begin_time = codemodel.card.begin_time;
            code.end_time = codemodel.card.end_time;
            code.membership_number = codemodel.card.membership_number;
            code.openid = codemodel.openid;
            code.bonus = codemodel.card.bonus;
            code.card_id = codemodel.card.card_id;
            code.code = codemodel.card.code;
            code.user_card_status = codemodel.user_card_status;
            return code;
        }

        private CodeModel QCode(string accessTokenOrAppId, string code, bool is_expire_dynamic_code = false,
            int timeOut = Config.TIME_OUT)
        {
            return ApiHandlerWapper.TryCommonApi(accessToken =>
            {
                var urlFormat = string.Format("https://api.weixin.qq.com/card/code/get?access_token={0}",
                    accessToken.AsUrlData());
                var data = new
                {
                    code = code,
                    is_expire_dynamic_code = is_expire_dynamic_code,
                };
                return CommonJsonSend.Send<CodeModel>(null, urlFormat, data, timeOut: timeOut);
            }, accessTokenOrAppId);
        }

        [HttpGet("UserinfoGet")]
        public Userinfo UserinfoGet(string appid, string code, string cardid)
        {
            try
            {
                WeChatCardProxy.WebApiEntity.Authorization_info Authorizate = GetAuthorization_info(appid);
                UserinfoGetResult Userinfo = CardApi.UserinfoGet(Authorizate.authorizer_access_token, cardid, code);
                if (Userinfo.errcode != 0)
                    return new Userinfo() {Errormodel = new ErrorModel() {desc = Userinfo.errmsg}};
                Userinfo info = MakeUserinfo(Userinfo);
                return info;
            }
            catch (Exception exe)
            {
                if (exe.Message != null)
                    return new Userinfo() {Errormodel = new ErrorModel() {desc = exe.Message}};
            }
            return new Userinfo();
        }

        private Userinfo MakeUserinfo(UserinfoGetResult userinfo)
        {
            Userinfo info = new Userinfo();
            UserinfoGetResult_UserInfo_Item item =
                userinfo.user_info.common_field_list.FirstOrDefault(
                    tr => tr.name == "USER_FORM_INFO_FLAG_MOBILE");
            if (item != null)
            {
                info.Phone = item.value;
            }
            info.openid = userinfo.openid;
            info.membership_number = userinfo.membership_number;
            return info;
        }
    }
}